package org.interaction3d.assembly.convert;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Michael Nischt
 */
public class Weld
{
    private final List<double[]> coordinateList = new ArrayList<double[]>();
    private final double epsilon;
    
    public Weld()
    {
        this(0);
    }

    public Weld(double epsilon)
    {
        if(epsilon < 0)
        {
            throw new IllegalArgumentException();
        }
        this.epsilon = epsilon;
    }


    public void clear()
    {
        coordinateList.clear();
    }

    public double[][] coordinates()
    {
        return coordinateList.toArray(new double[coordinateList.size()][]);
    }

    public int[] apply(double[]... coordinates)
    {
        int[] map = new int[coordinates.length];
        for(int i=0; i<map.length; i++)
        {
            map[i] = apply(coordinates[i]);
        }
        return map;
    }

    public int apply(double... coordinate)
    {
        if(coordinate.length < 1)
        {
            throw new IllegalArgumentException();
        }

        int size = coordinateList.size();
        for (int i = 0; i < size; i++) if (equals(coordinate, coordinateList.get(i)))
        {
            return i;
        }
        coordinateList.add(coordinate);
        return size;    
    }

    private boolean equals(double[] o1, double[] o2)
    {
        int len = o1.length;
        if (len != o2.length)
        {
            return false;
        }

        for (int i = 0; i < len; i++)
        {
            if (o1[i] + epsilon < o2[i] || o2[i] + epsilon < o1[i])
            {
                return false;
            }
        }
        return true;
    }
}
